<?php

namespace app\shop\controller;


use app\common\model\Account;
use app\common\model\ShopMember;
use app\common\service\Status;
use app\shop\controller\api\v1\Member;
use app\shop\model\ShopGoods;
use app\shop\model\ShopGoodsCate;
use app\shop\model\ShopOrder;
use app\shop\model\ShopOrderGoods;
use buildView\Filter;
use library\tools\Data;
use think\Controller;
use buildView\Form;
use buildView\Grid;
use think\facade\Cookie;
use app\common\model\User;
use think\facade\View;
use think\Db;

/**
 * 线下订单管理
 * Class OffLine
 * @package app\shop\controller
 */
class OffLine extends Controller
{
    /**
     * 选择换货商品
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/10/9 10:18
     */
    public function selectGoods()
    {
        $store = session('store');
        $grid = new Grid(new ShopGoods());
        $grid->model()->withSum('specs', 'stock')->withSum(['specs' => function ($q) {
            return 'sale_num';
        }], 'sale')->where('sid',$store['id']);
        $grid->logo('商品图片')->width(150)->image(5, 80, 80);
        $grid->column('cate_info', '所属分类')->display(function ($val, $data) {
            $html = "{$data['title']}";
            return $html;
        })->width(200)->align('left');
        $grid->column('price', '价格')->display(function ($val, $data) {
            return '￥' . $data['price'];
        })->width(150)->align('left');
        $grid->hideAction();

        $grid->filter(function (Filter $filter) {
            $filter->like('title', '商品名称');
            $cates = ShopGoodsCate::field('id,title as text,pid')->where('pid', 0)->where('id',18)->with(['son' => function ($q) {
                $store = session('store');
                $q->field('id,title as text,pid,sid')->where('sid',$store['id']);
            }])->select();
            $filter->eq('cate_id', '商品分类')->selectGroup($cates);
            $filter->eq('status', '商品状态')->select(Status::SHOPSTATUS());
        });
        $grid->hideExportButton();

        $grid->setIframe('submit', url('form'));
        return $grid->view();
    }

    /**
     * 移除选择商品
     * @auth true
     * @menu true
     */
    public function removeGood()
    {
        $good_id = $this->request->post('good_id');
        $cookieName = 'select_offline_goods';
        $good = cookie($cookieName);
        if (!empty($good)) {
            $goodArr = explode(',', $good);
            $key = array_search($good_id, $goodArr);

            if ($key !== false) {
                unset($goodArr[$key]);

                $value = implode(',', $goodArr);
                if (empty($value)) {
                    Cookie::delete($cookieName);
                } else {
                    cookie($cookieName, $value);
                }
            }
        }
        $this->success('成功');
    }

    /**
     * 生成线下订单页面
     * @auth true
     * @menu true
     */
    public function form()
    {
        $path = app()->getModulePath() . 'view/build_view/offlineOrder.html';
        $content = file_get_contents($path);
        $checkArr = cookie('checkArr');
        $selGoods = [];
        for ($i=0;$i<count($checkArr);$i++){
            $selGoods[$i] = ShopGoods::where('id',$checkArr[$i])->find();
        }
        $getMember = cookie('getMember');
        $inpUid = cookie('inpUid');
        $store = session('store');
        //选择商品的店铺商品数据
        $goodsData = ShopGoods::where('sid',$store['id'])->where('status',1)->where('is_deleted',0)->select();
        $this->assign([
            'store_id' => $store['id'],
            'goodsData' => $goodsData,
            'selGoods'=>$selGoods,
            'getMember'=>$getMember,
            'inpUid'=>$inpUid
        ]);

        return View::display($content);
    }

    //重置
    public function resetData(){
        Cookie::delete('checkArr');
        Cookie::delete('inpUid');
        Cookie::delete('getMember');
        $this->success('重置成功');
    }

    //扫描uid，获取Member信息
    public function getUidMember(){
        $uid = $_REQUEST['uid'];
        Cookie::set('inpUid',$uid);
        //判断会员id
        $user = User::where('id',$uid)->find();
        if(!$user){
            $this->error('无此会员，输入正确的会员码');
        }
        //获取Member
        $getMember = ShopMember::where('uid',$uid)->where('status',1)->where('is_deleted',0)->with(['card'])->select();
        $memberArr = [];
        foreach ($getMember as $val){
            $memberArr[]=[
                'id'=>$val['id'],
                'card_id'=>$val['card']['id'],
                'card_name'=>$val['card']['name'],
                'expire_time'=> date('Y-m-d',$val['expire_time'])
            ];
        }
        $eptimes = array_column($memberArr,'expire_time');
        array_multisort($eptimes,SORT_DESC,$memberArr);
        Cookie::set('getMember',$memberArr);
    }
    
    //提交线下订单
    public function submit(){
        $uid = $_REQUEST['uid'];
        $checkArr = $_REQUEST['goodsNav'];
        $mid = $_REQUEST['mid'];

        if (empty($checkArr)) {
            $this->error('请选择商品');
        }
        if($uid != 0){
            //验证是否存在会员
            $user = User::where('id',$uid)->find();
            if(!$user){
                $this->error('无此会员，输入正确的会员码');
            }
        }

        //生成订单号
        $order_sn = Data::uniqidDateCode();
        $price_express = 0;
        $goods_price = 0;
        $goods_num = 0;
        $visable = false;
        $store = session('store');

        //商品标题
        $title = '';
        if (count($checkArr) > 1) {
            $visable = true;
        }else{
            $title = $checkArr[0]['title'].$checkArr[0]['goods_num']."件";
        }
        foreach ($checkArr as $key => $data) {
            $goods_price += $data['price'] * $data['goods_num'];
            $goods_num += $data['goods_num'];
            if ($visable){
                $title .= $data['title'].$data['goods_num'].'件/';
            }
        }
        if ($visable){
            $data['title'] = substr($data['title'],0,-1);
        }

        //订单数据组装
        $orderData = [
            'uid'=>$uid,
            'title' => $title,
            'type' => 1,
            'store_id' => $store['id']?$store['id']:0,
            'order_no' => $order_sn,
            'freight_price' => $price_express,
            'buy_num' => $goods_num,
            'goods_price' => $goods_price,
            'pay_price' => $goods_price,
            'total_price' => $goods_price,
            'express_type' => 2,
            'pay_type' => 2,
            'is_pay' => 1,
            'pay_time' => date('Y-m-d H:i:s'),
            'status' => 2
        ];


        //验证会员卡
        $is_bed_goods_num = 0;
        if(!empty($mid)){
            foreach ($checkArr as $key => $value) {
                if ($value['is_bed'] == 1) {
                    $is_bed_goods_num += $value['goods_num'];
                }
            }
            $memberInfo = ShopMember::where('id',$mid)->where('status',1)->where('is_deleted',0)->find();
            if ($memberInfo['expire_time'] < time()){
                $this->error('此会员卡已过期');
            }
            if($memberInfo['total_num']-$memberInfo['use_num'] < $goods_num){
                $this->error('剩余洗衣次数不足'.$goods_num.'次');
            }
            if($memberInfo['bed_num']-$memberInfo['bed_use_num'] < $is_bed_goods_num){
                $this->error('剩余洗床品次数不足'.$is_bed_goods_num.'次');
            }
        }

        // 启动事务
        Db::startTrans();
        try {
            $shopOrder = new ShopOrder();
            $order = $shopOrder::create($orderData);

            if ($order){
                $orderGoods = [];
                foreach ($checkArr as $key => $data) {
                    //快照组装
                    $orderGoods[] = [
                        'order_id' => $order['id'],
                        'good_id' => $data['id'],
                        'good_title' => $data['title'],
                        'good_logo' => $data['logo'],
                        'price' => $data['price'],
                        'num' => $data['goods_num']
                    ];
                }
                $shopOrderGoods = new ShopOrderGoods();
                $shopOrderGoods->saveAll($orderGoods);

                $order_id = $shopOrderGoods->getLastInsID();
                Account::record($goods_price, $uid,"{$order['title']}",1,0,"",$store['id'],$order_id);
            }

            //增加已清洗的衣服件数（包括床品）
            $incUseNum = ShopMember::where('id',$mid)->setInc(use_num,$goods_num);

            //增加已使用的床品件数（不影响增加总件数）
            $incBedUseNum = ShopMember::where('id',$mid)->setInc(bed_use_num,$is_bed_goods_num);

            Cookie::delete('checkArr');
            Cookie::delete('inpUid');
            Cookie::delete('getMember');

            // 提交事务
            Db::commit();
            // 操作成功，返回结果
            return json(['code' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            // 操作失败，回滚事务
            Db::rollback();
            // 返回异常信息
            return json(['code' => 500, 'msg' => '事务处理错误--提交失败']);
        }
    }
    
    //选择的商品id,存到Cookie
    public function getCheckData(){
        $checkArr = $_REQUEST['checkArr'];
        
        $getCK = Cookie::get('checkArr');
        
        if(count($getCK) ==0){
            Cookie::set('checkArr',$checkArr);
        }elseif (count($getCK) > 0) {
            $merge = array_merge($getCK,$checkArr); 
            $arr = array_unique($merge);
            
            Cookie::set('checkArr',$arr);
        }
    }
    
    //移除选择商品
    public function reCheckData(){
        $id = $_REQUEST['id'];
        $checkArr = cookie('checkArr');
        $key = array_search($id, $checkArr);
        if ($key !== false){
            array_splice($checkArr, $key, 1);
        }
        // $arr = array_diff($checkArr,[$id]);
        
        Cookie::set('checkArr',$checkArr);
    }


//    public function form01()
//    {
//        $cookieName = 'select_offline_goods';
//        if ($this->request->isPut()) {
//            $good_ids = $this->request->put('select_ids');
//            $cookieName = 'select_offline_goods';
//            $good = cookie($cookieName);
//            if (!empty($good)) {
//                $good_ids = $good . ',' . $good_ids;
//            }
//            cookie($cookieName, $good_ids);
//            $this->success('选择完成');
//        }
//        $good_ids = cookie($cookieName);
//        $goods = ShopGoods::whereIn('id', $good_ids)->select();
//
//        $form = new Form(new ShopOrder());
//        $form->setSubmitText('生成线下订单');
//        $form->offline('order', '选择商品')->goodsArr($goods);
//        $form->textOfflineCardId('uid', '会员卡号')->help('无会员输入0')->required();
//
//        $form->saving(function ($post) use ($cookieName) {
//            $good = cookie($cookieName);
//            $goods = [];
//            if (!empty($good)) {
//                $goods = ShopGoods::whereIn('id',$good)->select()->toArray();
//            }else{
//                $this->error('请选择商品');
//            }
//
//            $user = User::where('id',$post['uid'])->find();
//            if(!$user){
//                $this->error('无此会员，输入正确的会员码');
//            }
//
//            $store = session('store');
//            $visable = false;
//            $order_sn = Data::uniqidDateCode();
//            $price_express = 0;
//            $goods_price = 0;
//            $goods_num = 0;
//            //商品标题
//            $title = '';
//            if (count($goods) > 1) {
//                $visable = true;
//            }else{
//                $title = $goods[0]['title'].$goods[0]['num']."件";
//            }
//            foreach ($goods as $key => $data) {
//                $goods_price += $data['price'] * $post['num'][$key];
//                $goods_num += $post['num'][$key];
//                if ($visable){
//                    $title .= $data['title'].$post['num'][$key].'件/';
//                }
//            }
//            if ($visable){
//                $data['title'] = substr($data['title'],0,-1);
//            }
//
//            //订单数据组装
//            $orderData = [
//                'uid'=>$post['uid'],
//                'title' => $title,
//                'type' => 1,
//                'store_id' => $store['id']?$store['id']:0,
//                'order_no' => $order_sn,
//                'freight_price' => $price_express,
//                'buy_num' => $goods_num,
//                'goods_price' => $goods_price,
//                'pay_price' => $goods_price,
//                'total_price' => $goods_price,
//                'express_type' => 2,
//                'pay_type' => 2,
//                'is_pay' => 1,
//                'pay_time' => date('Y-m-d H:i:s'),
//                'status' => 2
//            ];
//
////            $shopMemberModel = new ShopMember();
////            $uid = $post['uid'];
////            //原生SQL查询Member
////            $sql = "select * from shop_member where uid=".$uid." ORDER BY `expire_time` asc";
////            $rs = $shopMemberModel->query($sql);
//////            halt($rs);
//////            halt($goods_num);
////            if($rs[0]['total_num'] - $rs[0]['use_num'] > 0){
////                if($rs[0]['total_num'] - $rs[0]['use_num'] >= $goods_num){
////                    //剩余的件数足够洗衣件数
////                    $setDecOne = ShopMember::where('id',$rs[0]['id'])->setInc(use_num,$goods_num);
////
////                }else{
////                    //剩余的件数不足洗衣件数
////                    $surplus = $rs[0]['total_num'] - $rs[0]['use_num'];
////                    $more = $goods_num - $surplus;
////                    $setDecOne = ShopMember::where('id',$rs[0]['id'])->setInc(use_num,$surplus);
////                    $setDecTow = ShopMember::where('id',$rs[1]['id'])->setInc(use_num,$surplus);
////
////                }
////                halt(2222);
////            }
//
//
//            $order = ShopOrder::create($orderData);
//            if ($order){
//                $orderGoods = [];
//                foreach ($goods as $key => $data) {
//                    //快照组装
//                    $orderGoods[] = [
//                        'order_id' => $order['id'],
//                        'good_id' => $data['id'],
//                        'good_title' => $data['title'],
//                        'good_logo' => $data['logo'],
//                        'price' => $data['price'],
//                        'num' => $post['num'][$key]
//                    ];
//                }
//                (new ShopOrderGoods)->saveAll($orderGoods);
//                Account::record($goods_price, 0,"{$order['title']}",1,0,"",$store['id'],$order['id']);
//                Cookie::delete($cookieName);
//            }
//            return $post;
//        });
//        $form->saved(function ($post,$model){
//            ShopOrder::where('id',$model->id)->delete();
//        });
//        return $form->view();
//    }

}
